﻿using Coater.Helper;
using Coater.Helper.Modbus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Coater.Device.Io
{
    /// <summary>
    /// 德克维尔IO模块
    /// </summary>
    public class DecowellIO
    {
        IModbusHelper io { get; set; }
        /// <summary>
        /// modbus 从机地址
        /// </summary>
        public byte slaveAddress = 0x01;
        /// <summary>
        /// IP地址
        /// </summary>
        public string ConnectIp { get; set; }
        /// <summary>
        ///  端口
        /// </summary>
        public int ConnectPort { get; set; }
        /// <summary>
        /// 连接状态
        /// </summary>
        public bool IsOpen => io is { IsOpen: true };

        public bool Connect()
        {
            try
            {
                if (io is { IsOpen: true })
                {
                    return true;
                }
                io = new ModbusTCPHelper(ConnectIp, ConnectPort);


                return io is { IsOpen: true };
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog.Error(ex);
                return false;
            }
        }

        public bool? GetDI(ushort bit)
        {
            try
            {
                return io.ReadInputs(slaveAddress, bit, 1)[0];
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog.Error(ex);
                return null;
            }
        }

        public bool SetDO(ushort bit, bool bOn)
        {
            try
            {
                return io.WriteSingleCoil(slaveAddress, bit, bOn);
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog.Error(ex);
                return false;
            }
        }

        public bool? GetDO(ushort bit)
        {
            try
            {
                return io.ReadCoils(slaveAddress, bit, 1)[0];
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog.Error(ex);
                return null;
            }
        }


    }
}
